package com.xin.di.uav.applet.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xin.di.uav.mapper.BillMapper;
import com.xin.di.uav.applet.mapper.UserCompanyMapper;
import com.xin.di.uav.po.Bill;
import com.xin.di.uav.applet.service.IBillService;
import com.xin.di.uav.common.request.order.BillAddRequest;
import com.xin.di.uav.common.utils.BeanUtil;
import com.xin.di.uav.common.utils.Rs;
import com.xin.di.uav.user.entity.UserCompany;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author LTQ
 * @since 2023-07-03
 */
@Service
public class BillServiceImpl extends ServiceImpl<BillMapper, Bill> implements IBillService {

    @Autowired
    private BillMapper billMapper;

    @Autowired
    private UserCompanyMapper userCompanyMapper;

    @Override
    public void add(BillAddRequest billAddRequest) {
        Bill bill = BeanUtil.copyProperties(billAddRequest, Bill.class);
        billMapper.insert(bill);
    }

    @Override
    public Bill getByTcWaybillNo(String tcWaybillNo, Integer payStatus) {
        QueryWrapper<Bill> billQuery = new QueryWrapper<Bill>().eq("tc_waybill_no", tcWaybillNo).eq("pay_status", payStatus);
        return billMapper.selectOne(billQuery);
    }

    @Override
    public Bill getByTcWaybillNoAndType(String tcWaybillNo, Integer type) {
        QueryWrapper<Bill> billQuery = new QueryWrapper<>();
        return billMapper.selectOne(billQuery.lambda().eq(Bill::getTcWaybillNo, tcWaybillNo).eq(Bill::getType, type));
    }

    @Override
    public Rs<Boolean> billSettlement(BillAddRequest billAddRequest) {
        Bill bill = new Bill();
        bill.setPayStatus(2);
        bill.setUpdateTime(new Date());
        List<UserCompany> userCompanyList = new ArrayList<>(10);
        List<Map<String, Object>> billMapList = new ArrayList<>(10);
        bill.setProcessedBy(billAddRequest.getProcessedBy());
        billMapper.update(bill, new UpdateWrapper<Bill>().in("id", billAddRequest.getIdList()));
        if (!CollectionUtils.isEmpty(billAddRequest.getUserIdList())) {
            userCompanyList = userCompanyMapper.selectList(new QueryWrapper<UserCompany>().in("user_id", billAddRequest.getUserIdList()));
            QueryWrapper<Bill> billQueryWrapper = new QueryWrapper<Bill>().select("user_id as 'userId',sum(price_paid) as 'totalAccount'")
                    .in("id", billAddRequest.getIdList()).groupBy("user_id");
            billMapList = billMapper.selectMaps(billQueryWrapper);
        }
        if (!CollectionUtils.isEmpty(userCompanyList)) {
            List<Map<String, Object>> finalBillMapList = billMapList;
            userCompanyList.forEach(userCompany -> {
                if (!CollectionUtils.isEmpty(finalBillMapList)) {
                    finalBillMapList.forEach(finalBillMap -> {
                        if (userCompany.getUserId().equals(finalBillMap.get("userId"))) {
                            UserCompany userCompanyOne = new UserCompany();
                            userCompanyOne.setUsedCreditLimit(userCompany.getUsedCreditLimit().subtract(getBigDecimal(finalBillMap.get("totalAccount"))));
                            userCompanyMapper.update(userCompanyOne, new UpdateWrapper<UserCompany>().eq("user_id", userCompany.getUserId()));
                        }
                    });
                }
            });
        }
        return Rs.success();
    }

    public static BigDecimal getBigDecimal(Object value) {
        BigDecimal ret = null;
        if (value != null) {
            if (value instanceof BigDecimal) {
                ret = (BigDecimal) value;
            } else if (value instanceof String) {
                ret = new BigDecimal((String) value);
            } else if (value instanceof BigInteger) {
                ret = new BigDecimal((BigInteger) value);
            } else if (value instanceof Number) {
                ret = new BigDecimal(((Number) value).doubleValue());
            } else {
                throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass() + " into a BigDecimal.");
            }
        }
        return ret;
    }
}


